package com.xltq.dao.impl;

import com.xltq.dao.IProductDao;
import com.xltq.entity.Product;
import com.xltq.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class IProductDaoImpl implements IProductDao {
    private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
    @Override
    public long selectCountByTid(String tid) throws SQLException {
        String sql = "select count(1) from product where t_id = ?";
        return (Long) queryRunner.query(sql,new ScalarHandler(),tid);
    }

    @Override
    public List<Product> selectProductByPage(int page, int pageSize, String tid) throws SQLException {
        String sql = "select p_id as pid, t_id as tid, p_name as pname," +
                " p_time as ptime, p_image as pimage, p_price as pprice," +
                " p_state as pstate, p_info as pinfo from  product where t_id = ? limit ?,?";

        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class),tid,(page-1)*pageSize,pageSize);

    }
    @Override
    public Product selectProductByid(String pid) throws SQLException {
        String sql = "select p_id as pid, t_id as tid, p_name as pname," +
                " p_time as ptime, p_image as pimage, p_price as pprice," +
                " p_state as pstate, p_info as pinfo from  product where p_id = ?";

        return queryRunner.query(sql,new BeanHandler<Product>(Product.class),pid);
    }
}
